import ProTable from '@ant-design/pro-table';
import React, {useRef, useState} from 'react';
import {defaultPagination, paginationTool} from '@/utils/util';
import {useMount, useRequest} from 'ahooks';

import {edit, editKeys, findByPageList} from '@/services/ant-design-pro/poster';
import {Button, message, Modal, Transfer} from 'antd';
import {PlusOutlined} from '@ant-design/icons';

import {BetaSchemaForm, ProFormColumnsType, ProFormInstance} from '@ant-design/pro-form';
import {getResult} from "@/services/ant-design-pro/attribute";
import {TransferDirection} from "antd/lib/transfer";

interface RecordType {
  key: string;
  title: string;
  description: string;
}

var result = await getResult ( "systemposterkeyvalue", 1 );
const mockData: RecordType[] = result.map ( (_, i) => ({
  key: _?.value,
  title: _?.label,
  description: _?.label
}) );
const initialTargetKeys = mockData.filter ( item => Number ( item.key ) > 10 ).map ( item => item.key );
const cloneTbale = () => {
  const [targetKeys, setTargetKeys] = useState ( initialTargetKeys );
  const [selectedKeys, setSelectedKeys] = useState<string[]> ( [] );
  const formRef = useRef<ProFormInstance<API.Agent>> ();
  const [editDialg, setEditDialg] = useState ( false );
  const [agents, setAgents] = useState<API.Agent> ( {} );
  const [id, setId] = useState<Number> ( 0 );
  const [isModalOpen, setIsModalOpen] = useState ( false );


  const columns = [
    {
      title: '编号',
      dataIndex: 'index',
      key: 'index',
      valueType: 'indexBorder',
    },
    {
      title: '自动编号',
      dataIndex: 'id',
      key: 'id',
      search: false,
      hideInTable: true,
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '维语名称',
      dataIndex: 'nameUg',
      key: 'nameUg',
      search: false,
    },
    {
      title: '关键字',
      dataIndex: 'type',
      key: 'type'
    },

    {
      title: '操作',
      width: '164px',
      key: 'option',
      valueType: 'option',
      render: (_: any, row: API.Agent, index: number, action: any) => [
        <a
          key="link"
          onClick={(a) => {
            console.log ( row );
            setAgents ( row );
            editDialogInfo ( row, index );
          }}
        >
          编辑
        </a>,
        <a
          key="link"
          onClick={(a) => {
            // console.log ( row );
            let attr = row?.attr;
            setTargetKeys ( attr?.split ( "," ) )
            setId ( row?.id )
            showModal ()
          }}
        >
          数据编辑
        </a>,
      ],
    },
  ];

  const columnDialog: ProFormColumnsType<API.Agent>[] = [
    {
      title: '基本信息',
      valueType: 'group',
      columns: [
        {
          title: 'id',
          dataIndex: 'id',
          key: 'id',

          formItemProps: {
            hidden: true,
          },
        },
        {
          title: '名称',
          dataIndex: 'name',
          key: 'name',
          width: 'md',
          width: 'md',
          formItemProps: {
            rules: [
              {
                required: true,
                message: '此项为必填项',
              },
            ],
          },
        },
        {
          title: '维语名称',
          dataIndex: 'nameUg',
          key: 'nameUg',
          width: 'md',
          width: 'md',
          formItemProps: {
            rules: [
              {
                required: true,
                message: '此项为必填项',
              },
            ],
          },
        },
        {
          title: '关键字',
          dataIndex: 'type',
          key: 'type',
          width: 'md',
          valueType: 'digit',
          formItemProps: {
            rules: [
              {
                required: true,
                message: '此项为必填项',
              },
            ],
          },
        }
      ],
    },
  ];
  const [columnDialogs, setColumnDialogs] = useState ( columnDialog );

  const [pagination, setPagination] = useState<API.Pagination> ( defaultPagination () );
  const {
    run: fetchByPageList,
    refresh,
    data: dataList,
    loading,
  } = useRequest ( findByPageList, {
    debounceWait: 100,
    manual: true,
  } );
  const onChange = (nextTargetKeys: string[], direction: TransferDirection, moveKeys: string[]) => {
    //   console.log('targetKeys:', nextTargetKeys);
    //  console.log('direction:', direction);
    //  console.log('moveKeys:', moveKeys);
    setTargetKeys ( nextTargetKeys );
  };

  const onSelectChange = (sourceSelectedKeys: string[], targetSelectedKeys: string[]) => {
    //  console.log('sourceSelectedKeys:', sourceSelectedKeys);
    //   console.log('targetSelectedKeys:', targetSelectedKeys);
    setSelectedKeys ( [...sourceSelectedKeys, ...targetSelectedKeys] );
  };

  const onScroll = (direction: TransferDirection, e: React.SyntheticEvent<HTMLUListElement>) => {
    console.log ( 'direction:', direction );
    console.log ( 'target:', e.target );
  };
  useMount ( () => {
    fetchByPageList ();
  } );

  function hideEditDialg() {
    setAgents ( {...agents, id: 0} );
    formRef.current?.resetFields ();
    formRef?.current?.setFieldsValue ( {id: 0} );
    setEditDialg ( false );
  }

  function openEditDialg() {
    setAgents ( {id: 0} );
    formRef.current?.resetFields ();
    formRef?.current?.setFieldsValue ( {name: '', id: 0, nameUg: '', price: 0, level: 0} );
    setEditDialg ( true );
  }

  function editDialogInfo(row: API.Agent, index: number) {
    setAgents ( row );
    console.log ( 'editDialogInfo', row );
    formRef?.current?.setFieldsValue ( row );
    //  formRef?.current?.setFieldsValue ( {id: row.id}  );
    console.log ( 'editDialogInfo', formRef?.current?.getFieldsValue () );
    setEditDialg ( true );
  }

  const showModal = () => {
    setIsModalOpen ( true );
  };

  const handleOk = () => {
    console.log ( "Cancelling", targetKeys, id )
    if (targetKeys.length > 0) {
      let s = targetKeys.join ( "," );
      editKeys ( {attrs: s, id: id} ).then ( res => {
        let success = res.success
        if (success) {
          message.success ( "操作成功" )
          fetchByPageList ()
          setTargetKeys ( [] )

        } else {
          message.error ( "操作失败" )

        }
      } )
      setIsModalOpen ( false );
    }
  };

  const handleCancel = () => {

    setIsModalOpen ( false );
  };

  return (
    <div>

      <Modal title="数据选择" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
        <Transfer
          dataSource={mockData}
          titles={['源', '选择']}
          targetKeys={targetKeys}
          selectedKeys={selectedKeys}
          onChange={onChange}
          onSelectChange={onSelectChange}

          render={item => item.title}
        />
      </Modal>

      <BetaSchemaForm<API.Agent>
        formRef={formRef}
        initialValues={agents}
        onCancel={() => setEditDialg ( false )}
        onVisibleChange={setEditDialg}
        title="产品分类"
        visible={editDialg}
        layoutType="ModalForm"
        columns={columnDialogs}
        // @ts-ignore
        onFinish={async (values) => {
          // @ts-ignore
          //   values.id=category.id;
          //setCategory({...category,...values})

          //  values = Object.assign ( category, values )
          console.log ( agents, values );
          return new Promise<Boolean> ( (resolve, reject) => {
            edit ( values )
              .then ( () => {
                message.success ( '操作成功' );
                setEditDialg ( false );
                refresh ();
                resolve ( true );
              } )
              .catch ( () => {
                message.success ( '操作失败' );
                reject ( false );
              } );
          } );
        }}
      />
      <ProTable
        search={false}
        onDataSourceChange={(d) => {
          console.log ( 'onDataSourceChange', d );
        }}
        onLoad={(d) => {
          // 数据加载完操作
          console.log ( 'onDataSourceChange', d );
        }}
        toolBarRender={() => [
          <Button
            onClick={() => {
              formRef.current?.resetFields ();
              openEditDialg ();
            }}
            key="button"
            icon={<PlusOutlined/>}
            type="primary"
          >
            新建
          </Button>,
        ]}
        dataSource={dataList?.data?.list}
        loading={loading}
        pagination={paginationTool ( pagination, dataList?.data?.total, (data1: API.Pagination) => {
          setPagination ( data1 );

          fetchByPageList ( {...pagination} );
        } )}
        search={false}
        cardBordered={true}
        columns={columns}
      ></ProTable>
    </div>
  );
};

export default cloneTbale;
